//
//  HHProgressHUD.m
//  Flower
//
//  Created by 花花 on 2017/1/18.
//  Copyright © 2017年 花花. All rights reserved.
//

#import "HHProgressHUD.h"
#import "HHTextOnlyHUDView.h"
@implementation HHProgressHUD

+ (instancetype)shareInstance{

    static HHProgressHUD *instance = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc]init];
    });
    
    return instance;

}

- (instancetype)init{
    if (self == [super init]) {
        self.backgroundColor =[UIColor clearColor];
    }

    return self;
    
}
+(void)showStaus:(NSString *)staus andAutoHideAfterTimer:(CGFloat)showTime{

    HHProgressHUD *hudView =[HHProgressHUD shareInstance];
    
    HHTextOnlyHUDView *textView =[[HHTextOnlyHUDView alloc]init];
    textView.text = staus;
    [hudView setHubView:textView];
    [hudView showWithTime:showTime];


    
    
}

-(void)setHubView:(UIView *)hudView{


    [self addSubview:hudView];
}




-(void)showWithTime:(CGFloat)time{


    UIWindow *window =[[UIApplication sharedApplication]keyWindow];
    
    if (self.superview == nil) {
        [window addSubview:self];
    }
    
    if(time > 0){
        __weak typeof(self)weakSelf = self;
        delay(time, ^{
            __strong typeof(weakSelf) strongSelf  = weakSelf;
            
            if (strongSelf) {
                [strongSelf hide];
            }
        });
    
    
    }
    }

-(void)hide{
/// 首先移除先添加的
    UIView *firstHud = [self.subviews firstObject];
    
    if (firstHud) {
        [firstHud removeFromSuperview];
        if (self.subviews.count == 0) {
            [self removeFromSuperview];
        }
    }else{
    
        [self removeFromSuperview];
    }
    
    
}
- (void)hideAllHUDs{

    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    [self removeFromSuperview];

}

/// 这里直接使用了GCD
static void delay(CGFloat time, dispatch_block_t block) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (block) {
            block();
        }
    });
}

@end
